package com.xingzhe.pengji.security.support;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.xingzhe.pengji.security.domain.User;
import com.xingzhe.pengji.security.services.UserService;

public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter
{

    @Autowired
    private UserService<User> userService;

    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";

    private static final Log log = LogFactory.getLog(MyUsernamePasswordAuthenticationFilter.class);

    // private static final String VALIDATE_CODE = "validateCode";

    private static final String SESSION_VALUE = "SPRING_SECURITY_LAST_USERNAME";

    // public MyUsernamePasswordAuthenticationFilter(UserService userService){
    // this.userService=userService;
    // }

    public static String getAuthenticatedUsername()
    {
        String username = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails)
        {
            username = ((UserDetails) principal).getUsername();
        }
        else
        {
            username = principal.toString();
        }
        return username;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException
    {
        HttpSession session = request.getSession();
        session.setAttribute("ERROR_USER_NAME", null);
        session.setAttribute("ERROR_PASSWORD", null);
        // 检测验证码
        // checkValidateCode(request);

        if (!request.getMethod().equals("POST"))
        {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String userName = obtainUsername(request);
        String password = obtainPassword(request);
        if ("" == userName)
        {
            if ("" == password)
            {
                session.setAttribute("ERROR_USER_NAME", "用户名不得为空");
                session.setAttribute("ERROR_PASSWORD", "密码不得为空");
                throw new AuthenticationServiceException("用户名和密码不得为空");
            }
            request.setAttribute("ERROR_USER_NAME", "用户名不得为空");
            throw new AuthenticationServiceException("用户名不得为空");

        }
        else
        {
            if ("" == password)
            {
                session.setAttribute(SESSION_VALUE, userName);
                session.setAttribute("ERROR_PASSWORD", "密码不得为空");
                throw new AuthenticationServiceException("用户名和密码不得为空");
            }
        }

        // 验证用户账号与密码是否对应
        User user = this.userService.getUserByAccount(userName.trim());
        if (user == null)
        {
            session.setAttribute("ERROR_USER_NAME", "用户不存在");
            throw new AuthenticationServiceException("该用户不存在！");
        }
        if (!user.getPassword().equals(password))
        {
            session.setAttribute("ERROR_PASSWORD", "密码错误！");
            throw new AuthenticationServiceException("密码错误！");
        }
        session.setAttribute("ERROR_USER_NAME", null);
        session.setAttribute("ERROR_PASSWORD", null);
        session.setAttribute(SESSION_VALUE, userName);
        log.info("登入成功！");
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
        // 允许子类设置详细属性
        setDetails(request, authRequest);

        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    // protected void checkValidateCode(HttpServletRequest request) {
    // HttpSession session = request.getSession();
    //
    // String sessionValidateCode = obtainSessionValidateCode(session);
    // //让上一次的验证码失效
    // session.setAttribute(VALIDATE_CODE, null);
    // String validateCodeParameter = obtainValidateCodeParameter(request);
    // if (""==validateCodeParameter|| !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
    // throw new AuthenticationServiceException("验证码错误！");
    // }
    // }
    //
    // private String obtainValidateCodeParameter(HttpServletRequest request) {
    // Object obj = request.getParameter(VALIDATE_CODE);
    // return null == obj ? "" : obj.toString();
    // }
    //
    // protected String obtainSessionValidateCode(HttpSession session) {
    // Object obj = session.getAttribute(VALIDATE_CODE);
    // return null == obj ? "" : obj.toString();
    // }

    @Override
    protected String obtainUsername(HttpServletRequest request)
    {
        Object obj = request.getParameter(USERNAME);
        return null == obj ? "" : obj.toString();
    }

    @Override
    protected String obtainPassword(HttpServletRequest request)
    {
        Object obj = request.getParameter(PASSWORD);
        return null == obj ? "" : obj.toString();
    }

}
